package com.mediacloud.app.newsmodule.view;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.Address;
import com.chinamcloud.collect.AcquisitionManager;
import com.loopj.android.http.RequestParams;
import com.mediacloud.app.appfactory.cache.AppConfig;
import com.mediacloud.app.assembly.interfaces.LoadNetworkBack;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.BaseMessageReciver;
import com.mediacloud.app.model.utils.DefaultBgUtil;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.model.NewsCommentItem;
import com.mediacloud.app.newsmodule.model.ReplyCommentItem;
import com.mediacloud.app.newsmodule.model.ReplyListHelper;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.CommentPublishInvoker;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.LoginUtils;
import com.mediacloud.app.newsmodule.utils.ToastUtil;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.reslib.util.HTTPClient;
import com.mediacloud.app.reslib.util.RequestParamsX;
import com.mediacloud.app.reslib.view.SimpleDialog;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.app.user.utils.DeviceInfo;


@Deprecated
public class CommentInputView extends RelativeLayout {

    public TextView writeComment;
    public View cancelComment;
    public EditText commentInputText;
    public ArticleItem articleItem;
    public RelativeLayout topLayout;
    public CommentPublishInvoker commentPublishInvoker;
    SubmitCommentCallBack callBack;
    public SubmitCommentListener commentListener;
    public SimpleDialog simpleDialog;
    protected Context mContext;
    public boolean isReply = false;
    public int type = 1;

    public CommentInputView(Context context) {
        this(context, null);
    }

    public CommentInputView(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflate(context, R.layout.aappfactory_layout_comment_input, this);
        initChild(context);
        mContext = context;
    }

    public CommentInputView(Context context, AttributeSet attrs,
                            int defStyleAttr) {
        this(context, attrs);
    }

    protected void initChild(final Context context) {
        simpleDialog = new SimpleDialog(context);
        callBack = new SubmitCommentCallBack();
        commentPublishInvoker = new CommentPublishInvoker(callBack);
        topLayout = findViewById(R.id.topLayout);
        writeComment = findViewById(R.id.writeComment);
        cancelComment = findViewById(R.id.cancelComment);

        setAnonymousView();
        commentInputText = findViewById(R.id.commentInputText);
        float size = getResources().getDimensionPixelSize(R.dimen.dime_fifteendp);
        commentInputText.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
        commentInputText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (commentInputText.getText().length() > 0) {
                    writeComment.setTextColor(DefaultBgUtil.getTintColor(mContext));
                } else {
                    writeComment.setTextColor(0x999999);
                }
            }
        });
        commentInputText.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    InputMethodManager imm = (InputMethodManager) writeComment
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                }
            }
        });
        writeComment.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (isReply) {
                    submitReplay();
                } else {
                    if (commentInputText.getText().length() == 0) {
                        ToastUtil.show(context, R.string.comment_cantnull);
                        return;
                    }
                    UserInfo info = UserInfo.getUserInfo(context);
                    if (info.isLogin()) {
                        simpleDialog.show();
                        simpleDialog.updateText(R.string.comment_submit);
                        // String nickName=info.getNickname();
                        String uid = info.getUserid();
                        // if(TextUtils.isEmpty(nickName))
                        // nickName=getResources().getString(R.string.anonymous_commentname);
                        commentPublishInvoker.publishComment(type,
                                info.getAvatar(),
                                info.getNickname(),
                                articleItem, uid,
                                commentInputText.getText().toString(),
                                mous,
                                context);
                        iniAnonymousStatus();
                    } else {
                        intoLogin(context);
                    }
                }
            }
        });
    }

    /**
     * 匿名和共享地理位置相关
     */
    public CheckBox anonymousCheckBox;
    public int mous = 0;

    protected void setAnonymousView() {
        anonymousCheckBox = findViewById(R.id.anonymousCheckBox);
        if (AppFactoryGlobalConfig.getAppServerConfigInfo(mContext).getOtherFunction() != null && AppFactoryGlobalConfig.getAppServerConfigInfo(mContext).getOtherFunction().getAnonymous_comment() <= 0)//getResources().getString(R.string.needAnonymous).equals("0"))
            anonymousCheckBox.setVisibility(View.GONE);
        anonymousCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (compoundButton.isChecked()) {
                    anonymousCheckBox.setTextColor(getResources().getColor(R.color.mousColor));
                    mous = 1;
                } else {
                    mous = 0;
                    anonymousCheckBox.setTextColor(getResources().getColor(R.color.color_999));
                }
            }
        });

    }

    protected void iniAnonymousStatus() {
        mous = 0;
        anonymousCheckBox.setChecked(false);
    }


    String comment_id;


    String reply_avatar;
    String reply_nickname;
    String reply_uid;

    public void setReplyData(NewsCommentItem data) {
        comment_id = "" + data.getCommentid();
        reply_avatar = data.getAvatar();
        reply_nickname = data.getNickname();
        reply_uid = data.getUid();
    }

    public void setReplyData(ReplyCommentItem obj) {
        comment_id = "" + obj.getParentCid();
        reply_avatar = obj.getAvatar();
        reply_nickname = obj.getNickName();
        reply_uid = obj.getUid();
    }


    private void submitReplay() {
        if (commentInputText.getText().length() == 0) {
            ToastUtil.show(getContext(), R.string.comment_cantnull);
            return;
        }

        UserInfo info = UserInfo.getUserInfo(getContext());
        if (info.isLogin()) {
            simpleDialog.show();
            simpleDialog.updateText(R.string.comment_submit);
            // String nickName=info.getNickname();

            // if(TextUtils.isEmpty(nickName))
            // nickName=getResources().getString(R.string.anonymous_commentname);


            String uid = info.getUserid();
            String interfaces = "api/comment/reply";
            RequestParams param = new RequestParamsX();
            param.put("anonymous", "0");
            param.put("avatar", info.getAvatar());
            param.put("comment_id", comment_id);
            param.put("content", commentInputText.getText().toString());
            param.put("nickname", info.getNickname());
            param.put("rela_id", String.valueOf(articleItem.getId()));
            param.put("reply_avatar", reply_avatar);
            param.put("reply_nickname", reply_nickname);
            param.put("reply_uid", reply_uid);
            param.put("uid", uid);
            param.put("anonymous_flag", mous + "");
           // AppConfig config = new AppConfig(mContext);
            if (true) {
                String latandlon = AppFactoryGlobalConfig.getLongitude() + "," + AppFactoryGlobalConfig.getLatitude();
                if (latandlon.length() < 2)
                    latandlon = "";
                String area_grade = "";
                if (AppFactoryGlobalConfig.getAddress() != null) {
                    Address address = AppFactoryGlobalConfig.getAddress();
                    area_grade = address.province + "," + address.city + "," + address.district;
                }
                param.put("latandlon", latandlon);
                param.put("area_grade", area_grade);
            }
            if (AppFactoryGlobalConfig.getAddress() != null) {
                param.put("location", AppFactoryGlobalConfig.getAddressStr());
            }
            param.put("phone_type", DeviceInfo.getDeviceInfo(mContext).getDeviceInfo4Server().device_model);
            param.put("device_id", DeviceInfo.getDeviceInfo(mContext).getDeviceInfo4Server().device_flag);
            HTTPClient helper = new HTTPClient();
            helper.postData(DataInvokeUtil.ServerURL + interfaces, param, new LoadNetworkBack<ReplyListHelper>() {

                @Override
                public void Success(ReplyListHelper result) {
                    simpleDialog.dismiss();
                    if (result.state) {

                        //数据采集
                        final UserInfo info = UserInfo.getUserInfo(getContext());
                        String comment = commentInputText.getText().toString();
                        AcquisitionManager p = AcquisitionManager.getInstance();
                        if (articleItem != null) {
                            p.comment(info, articleItem.getId() + "", DomainUtil.getDomain(articleItem.getUrl())
                                    , articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent(), comment);
                        }

                        commentInputText.getText().clear();
                        ToastUtil.showCustomView(getContext(), R.string.comment_success);
                        Addintegral.addintegral(getContext(), articleItem.getId(), 3, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0",articleItem);
                        if (commentListener != null)
                            commentListener.success();
                    } else {
                        Failure(null);
                    }
                }

                @Override
                public void Failure(Object obj) {
                    Log.w(VIEW_LOG_TAG, "fault" + obj);
                    ToastUtil.show(getContext(), R.string.comment_failed);
                    if (commentListener != null)
                        commentListener.failed();
                    simpleDialog.dismiss();
                }

                @Override
                public void otherData(String result) {
                }
            }, new ReplyListHelper());
        } else {
            intoLogin(getContext());
        }
        //   AppAgent.onEvent(mContext, AnalyticsTpye.COMMENT_REPLY_SUBMIT);
        iniAnonymousStatus();

    }

    public interface SubmitCommentListener {
        void success();

        void failed();
    }

    protected void intoLogin(Context context) {
//        ToastUtil.show(context, R.string.please_login);
//        Intent intent = new Intent();
//        intent.setClassName(context, ModuleReferenceConfig.LoginActivity);
//        context.startActivity(intent);
        LoginUtils.request_source =LoginUtils.source_comment;
        LoginUtils.invokeLogin(context);
    }

    class SubmitCommentCallBack implements
            DataInvokeCallBack<BaseMessageReciver> {

        @Override
        public void success(BaseMessageReciver data) {
            simpleDialog.dismiss();
            if (data.state) {
                //评论数据采集
                final UserInfo info = UserInfo.getUserInfo(getContext());
                String comment = commentInputText.getText().toString();
                AcquisitionManager p = AcquisitionManager.getInstance();
                p.comment(info, articleItem.getId() + "", DomainUtil.getDomain(articleItem.getUrl())
                        , articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent(), comment);

                commentInputText.getText().clear();
                ToastUtil.showCustomView(getContext(), R.string.comment_success);
                //   AppAgent.onEvent(mContext, AnalyticsTpye.COMMENT_SUBMIT_SUCCESS);
                Addintegral.addintegral(getContext(), articleItem.getId(), 3, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0",articleItem);
                if (commentListener != null)
                    commentListener.success();
            } else {
                fault(null);
            }
            Log.w(VIEW_LOG_TAG, "success" + data);
        }

        @Override
        public void fault(Object data) {
            Log.w(VIEW_LOG_TAG, "fault" + data);
            ToastUtil.show(getContext(), R.string.comment_failed);
            if (commentListener != null)
                commentListener.failed();
            simpleDialog.dismiss();
        }

    }

    public void show() {
        ViewTreeObserver vto = commentInputText.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                if (commentInputText.isShown()) {
                    commentInputText.setFocusable(true);
                    commentInputText.setFocusableInTouchMode(true);
                    commentInputText.requestFocus();
                    // InputMethodManager imm = (InputMethodManager)
                    // writeComment.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    // imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                    commentInputText.setSelection(commentInputText.getText().length());
                }
            }
        });

    }

    public void hide() {
        setVisibility(View.GONE);
        InputMethodManager inputmanger = (InputMethodManager) writeComment
                .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputmanger.hideSoftInputFromWindow(commentInputText.getWindowToken(),
                0);
    }

    public void destory() {
        if (simpleDialog != null)
            simpleDialog.dismiss();
        simpleDialog = null;
        commentListener = null;
        if (commentPublishInvoker != null)
            commentPublishInvoker.destory();
        commentPublishInvoker = null;
    }

}